Zigzag conversion¶
Time: O(N); Space: O(1); easy
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”
Notice that zigzag extends according to the directions of down->up-right->down->up-right…
| /| /|
| / | / | ...
| / | / | ...
|/ |/ |/
Write the code that will take a string and make this conversion given a number of rows:
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
After conversion, we get
P I N A L S I G Y A H R P I
Read line by line, the answer is “PINALSIGYAHRPI”.
Example 3:
Input: s = “PAYPALISHIRING”, numRows = 1
Output: “PAYPALISHIRING”
Explanation:
After conversion, we get PAYPALISHIRING
Read line by line, the answer is “PAYPALISHIRING”.
[1]:
class Solution1(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
step, zigzag = 2 * numRows - 2, ""
for i in range(numRows):
for j in range(i, len(s), step):
zigzag += s[j]
if 0 < i < numRows - 1 and j + step - 2 * i < len(s):
zigzag += s[j + step - 2 * i]
return zigzag
[2]:
sol = Solution1()
s = "PAYPALISHIRING"
numRows = 3
assert sol.convert(s, numRows) == "PAHNAPLSIIGYIR"
s = "PAYPALISHIRING"
numRows = 4
assert sol.convert(s, numRows) == "PINALSIGYAHRPI"
s = "PAYPALISHIRING"
numRows = 1
assert sol.convert(s, numRows) == "PAYPALISHIRING"